﻿using Micro.Extensions.DDD.Bus;
using Micro.Extensions.DDD.Notifications;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Micro.Extensions.DDD.Commands
{
    /// <summary>
    /// 领域命令处理程序
    /// 用来作为全部处理程序的基类，提供公共方法和接口数据
    /// </summary>
    public abstract class CommandHandler
    {
        /// <summary>
        /// 注入中介处理接口（目前用不到，在领域事件中用来发布事件）
        /// </summary>
        protected readonly IMediatorHandler _bus;

        /// <summary>
        /// 构造函数注入
        /// </summary>
        /// <param name="uow"></param>
        /// <param name="bus"></param>
        /// <param name="cache"></param>
        public CommandHandler(IMediatorHandler bus)
        {
            _bus = bus;
        }


        //将领域命令中的验证错误信息收集
        //目前用的是缓存方法（以后通过领域通知替换）
        protected void NotifyValidationErrors(Command message)
        {
            List<string> errorInfo = new List<string>();
            foreach (var error in message.ValidationResult.Errors)
            {
                //errorInfo.Add(error.ErrorMessage);

                //将错误信息提交到事件总线，派发出去
                _bus.PublishEvent(new DomainNotification("", error.ErrorMessage));
            }

            //将错误信息收集一：缓存方法（错误示范）
            //_cache.Set("ErrorData", errorInfo);
        }


        protected void AddError(string mensagem)
        {
            _bus.PublishEvent(new DomainNotification("", mensagem));
        }
        protected void AddError(string key, string mensagem)
        {
            _bus.PublishEvent(new DomainNotification(key ?? "", mensagem));
        }

    }
}
